<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="name" label="房间名" required>
        <uni-easyinput placeholder="填写房间名" v-model="formData.name" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="address" label="地址" required>
        <uni-easyinput placeholder="请填写具体位置" type="textarea" v-model="formData.address" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="area" label="面积" required>
        <uni-easyinput placeholder="请填写具体面积" type="number" v-model="formData.area"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="houseType" label="户型" required>
        <uni-data-select :localdata="[
          {value:'1室0厅1卫',text:'1室0厅1卫'},
          {value:'1室1厅1卫',text:'1室1厅1卫'},
          {value:'2室1厅1卫',text:'2室1厅1卫'},
          {value:'2室2厅1卫',text:'2室2厅1卫'},
          {value:'3室1厅1卫',text:'3室1厅1卫'},
          {value:'3室2厅2卫',text:'3室2厅2卫'},
          {value:'4室2厅2卫',text:'4室2厅2卫'}
        ]" placeholder="请填写户型" v-model="formData.houseType"></uni-data-select>
      </uni-forms-item>
      <uni-forms-item name="price" label="月租金" required>
        <uni-easyinput placeholder="请填写月租金" type="number" v-model="formData.price"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="floor" label="楼层">
        <uni-easyinput placeholder="请填写楼层信息，如：6/18层" v-model="formData.floor"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="orientation" label="朝向">
        <uni-data-select :localdata="formOptions.orientation_localdata" v-model="formData.orientation"></uni-data-select>
      </uni-forms-item>
      <uni-forms-item name="decoration" label="装修">
        <uni-data-select :localdata="formOptions.decoration_localdata" v-model="formData.decoration"></uni-data-select>
      </uni-forms-item>
      <uni-forms-item name="facilities" label="配套设施">
        <uni-data-checkbox :multiple="true" :localdata="[
          {value:'冰箱',text:'冰箱'},
          {value:'洗衣机',text:'洗衣机'},
          {value:'空调',text:'空调'},
          {value:'热水器',text:'热水器'},
          {value:'电视',text:'电视'},
          {value:'WiFi',text:'WiFi'},
          {value:'衣柜',text:'衣柜'},
          {value:'沙发',text:'沙发'},
          {value:'床',text:'床'},
          {value:'暖气',text:'暖气'},
          {value:'燃气灶',text:'燃气灶'}
        ]" v-model="formData.facilities"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="images" label="房屋图片">
        <uni-file-picker :limit="9" file-mediatype="image" mode="grid" file-extname="jpg,jpeg,png,webp" return-type="array" v-model="formData.images"></uni-file-picker>
      </uni-forms-item>
      <uni-forms-item name="tenant_id" label="租户ID">
        <uni-data-select collection="tenants" field="name as text, _id as value" placeholder="关联的租户ID" v-model="formData.tenant_id"></uni-data-select>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/houses.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'houses';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "name": "",
        "address": "",
        "area": 1,
        "houseType": "",
        "price": 100,
        "deposit": "",
        "floor": "",
        "orientation": "",
        "decoration": "",
        "facilities": [],
        "images": [],
        "status": "空置中",
        "tenant_id": ""
      }
      return {
        formData,
        formOptions: {
          "deposit_localdata": [
            {
              "value": "押一付一",
              "text": "押一付一"
            },
            {
              "value": "押一付二",
              "text": "押一付二"
            },
            {
              "value": "押一付三",
              "text": "押一付三"
            },
            {
              "value": "押二付三",
              "text": "押二付三"
            },
            {
              "value": "半年付",
              "text": "半年付"
            },
            {
              "value": "年付",
              "text": "年付"
            }
          ],
          "orientation_localdata": [
            {
              "value": "东",
              "text": "东"
            },
            {
              "value": "南",
              "text": "南"
            },
            {
              "value": "西",
              "text": "西"
            },
            {
              "value": "北",
              "text": "北"
            },
            {
              "value": "东南",
              "text": "东南"
            },
            {
              "value": "东北",
              "text": "东北"
            },
            {
              "value": "西南",
              "text": "西南"
            },
            {
              "value": "西北",
              "text": "西北"
            }
          ],
          "decoration_localdata": [
            {
              "value": "毛坯",
              "text": "毛坯"
            },
            {
              "value": "简装",
              "text": "简装"
            },
            {
              "value": "精装",
              "text": "精装"
            },
            {
              "value": "豪装",
              "text": "豪装"
            }
          ],
          "status_localdata": [
            {
              "value": "已出租",
              "text": "已出租"
            },
            {
              "value": "空置中",
              "text": "空置中"
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onLoad(e) {
      if (e.id) {
        const id = e.id
        this.formDataId = id
        this.getDetail(id)
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).doc(this.formDataId).update(value).then((res) => {
          uni.showToast({
            title: '修改成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      },

      /**
       * 获取表单数据
       * @param {Object} id
       */
      getDetail(id) {
        uni.showLoading({
          mask: true
        })
        db.collection(dbCollectionName).doc(id).field("name,address,area,houseType,price,deposit,floor,orientation,decoration,facilities,images,tenant_id").get().then((res) => {
          const data = res.result.data[0]
          if (data) {
            this.formData = data
            
          }
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        }).finally(() => {
          uni.hideLoading()
        })
      }
    }
  }
</script>
